package com.dayu.finecomm.aop;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * AOP日志代理
 * 
 * @author XuJialiang
 * @since 2017-11-10 14:45:15
 * @version V1.0.0
 */
@Service
public class AopProxy {
	static Logger LOGGER = LoggerFactory.getLogger(AopProxy.class);

	private volatile static AopProxy mSelf = null;

	private ApplicationContext mApplicationContext = null;

	private Boolean mInitialization = false;

	/**
	 * AopLogManager
	 */
	@Resource
	AopLogManager mAopLogManager;

	/**
	 * AopLogService
	 */
	@Autowired
	AopLogService mAopLogService;

	public static AopProxy instance() {
		if (null == mSelf) {
			synchronized (AopProxy.class) {
				if (null == mSelf) {
					mSelf = new AopProxy();
				}
			}
		}

		return mSelf;
	}

	public AopProxy() {
		LOGGER.info("AopProxy Initialization");

		mSelf = this;
	}

	/**
	 * 获取日志管理集中器
	 * 
	 * @return
	 */
	public AopLogManager getAopLogManager() {
		if (false == mInitialization) {
			synchronized (mInitialization) {
				if (false == mInitialization) {
					mInitialization = true;

					/**
					 * 申明一个容量为1000的队列
					 */
					BlockingQueue<AopLogItem> queue = new LinkedBlockingQueue<AopLogItem>(
							10000);

					mAopLogManager.init(queue);

					mAopLogService.start(queue);
				}
			}
		}

		return mAopLogManager;
	}

	/**
	 * 设置上下文
	 * 
	 * @param applicationContext
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {
		mApplicationContext = applicationContext;
	}

	/**
	 * 为被代理对象创建一个AOP代理
	 * 
	 * @param clazz
	 * @param obj
	 * @return
	 */
	public <T> T createAopProxy(Class<T> clazz, T obj) {
		T ret = null;

		if (null != mApplicationContext) {
			try {
				DefaultPointcutAdvisor advisor = (DefaultPointcutAdvisor) mApplicationContext
						.getBean("userLogAdvisor");

				ProxyFactory weaver = new ProxyFactory();
				weaver.setTarget(obj);
				weaver.addAdvisor(advisor);

				ret = clazz.cast(weaver.getProxy());

			} catch (Exception e) {
				ret = clazz.cast(obj);

				LOGGER.error("Create aop proxy failed: " + e);
			}

		} else {
			ret = clazz.cast(obj);

			LOGGER.error("ApplicationContext is null");
		}

		return ret;
	}
}
